clear all

current_directory = pwd;
diary sigma_3_refined_search_3.out
parpool('local',16)
rng(17)

output_line = [];
%dlmwrite('partial_spillover_fixed_theta_psi.csv',output_line)

%%% These are the target moments
growth = 3.01;
relative_wage = 1.29;
share_employment_entry = 0.144;
agg_export_revenue_share = 0.1017;
var_TFPR = 0.0116;
diff_TFPR = 0.066;
trade_elasticity_avg = -5;
targets = [growth;...
               growth;...
               relative_wage-1;...
               share_employment_entry;...
               agg_export_revenue_share;...
               var_TFPR;...
               trade_elasticity_avg];               

%%% These are the upper and lower bounds for the parameter estimates
%%% [lambda_US; eta_US; mu_OECD; trade_cost; theta; psi]
%%% The last two values are kappa and nu.

lb =  [0.06;    0.025;    0.085;      1.5;       4.25;      0.55];
ub = [0.08;    0.035;    0.12;          1.65;       5;       0.7];

mid_bound=(lb+ub)/2;
all_distance = [];
    for repeats = 1:1:1
        x0 = [lb , (ub - lb)/6 + lb , (ub - lb)/3 + lb , (ub - lb)/2 + lb] + floor(repeats) * repmat(mid_bound,1,4);
        if max(all_distance)<1e-3
            [params_out,end_targets,prev_distance] = sim_annealing_parallel(@steady_state_simulation_repeats_run,targets,x0,ub,lb,1000);
        else
            [params_out,end_targets,prev_distance] = sim_annealing_parallel(@steady_state_simulation_repeats_run,targets,x0,ub,lb,1500);
        end
        all_distance(end+1)=prev_distance;
        output_line = [reshape(params_out(:,1),1,size(params_out,1)),reshape(end_targets,1,length(end_targets))];
          dlmwrite('sigma_3_refined_search_3.csv',output_line,'-append')
          system(['mail -a ''' current_directory '/sigma_3_refined_search_3.csv'' -s "new parameter estimates" inath33@gmail.com  < /dev/null'])
    end
%end
    
poolobj = gcp('nocreate');
delete(poolobj);

diary off
